using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;


namespace XmlFieldType
{
    public class SPFieldXmlBase : SPField
    {
        public SPFieldXmlBase(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
        }

        public SPFieldXmlBase(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
        }

        public override BaseFieldControl FieldRenderingControl
        {
            get
            {
                BaseFieldControl fieldControl = new BaseXmlField(this);

                fieldControl.FieldName = InternalName;

                return fieldControl;
            }
        }

        public override Type FieldValueType
        {
            get
            {
                return typeof(XmlDocument);
            }
        }

        public override string DefaultValue
        {
            get
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(this.SchemaXml);

                XmlNode nodeInFieldSchema = doc.SelectSingleNode("Field/Default");

                if (nodeInFieldSchema != null)
                {
                    return nodeInFieldSchema.InnerXml;
                }
                return null;

            }
            set
            {
                base.DefaultValue = value;
            }
        }

        public override string GetValidatedString(object value)
        {
            if ((this.Required == true) && ((value == null) || ((String)value == "")))
            {
                throw new SPFieldValidationException(string.Format("{0} must have a value.",this.Title));
            }
            else
            {
                //Don't attempt to load it if it's blank
                if (!((value == null) || ((String)value == "")))
                {
                    XmlDocument doc = new XmlDocument();

                    try
                    {
                        doc.LoadXml(value.ToString());
                    }
                    catch (XmlException ex)
                    {
                        throw new SPFieldValidationException(string.Format("{0} has an invalid value. {1}", this.Title, ex.Message), ex);
                    }
                }
                return base.GetValidatedString(value);

            }

        }

        public virtual XmlDocument GetFieldXml(string value)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(value);

            return doc;
        }

    }

}
